<?php


namespace Beerus\Modules\SuperSubsidy\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\SuperSubsidy\YouZanBrandItemModel;
use Biz\model\SuperSubsidy\YouZanBrandUserModel;
use Biz\model\SuperSubsidy\YouZanDeliverRecordModel;
use Biz\model\SuperSubsidy\YouZanOrders;
use Biz\service\SuperSubsidy\YouZanBrand;
use Biz\service\SuperSubsidy\YouZanDeliver;
use Biz\service\SuperSubsidy\YouZanOrder;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use PHPExcel_Cell_DataValidation;
use PhpOffice\PhpSpreadsheet\IOFactory;

class SubsidyBrandItemsController extends Controller
{
    const PAGE_SIZE = 20;

    public function itemList(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $itemId = trim($request->input('item_id', 0));
        $itemName = trim($request->input('item_name', ''));
        $brandName = trim($request->input('brand_name', ''));
        $brandUserId = trim($request->input('brand_user_id', 0));
        if ($itemId) {
            $where['item_id'] = trim($itemId);
        } else if ($itemName) {
            $where['item_name[~]'] = $itemName;
        } else if ($brandUserId) {
            $where['brand_user_id'] = $brandUserId;
        }
        $where['LIMIT'] = $limit;
        // 处理查询条件
        $list = YouZanBrandItemModel::selectByWhere($where);
        $brandUserIds = $list ? array_column($list, 'brand_user_id') : [];
        $brandUserList = $brandUserIds ? YouZanBrandUserModel::selectByWhere(['id' => $brandUserIds]) : [];
        $brandUserList = $brandUserList ? array_column($brandUserList, null, 'id') : [];
        foreach ($list as &$row) {
            $row['brand_name'] = $brandUserList[$row['brand_user_id']]['brand_name'] ?? '';
        }
        $brandOption = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $brandOption = array_column($brandOption, 'brand_name', 'id');
        unset($where['LIMIT']);
        $total = YouZanBrandItemModel::count($where);
        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $brandOption) {
            $grid->tools(function ($tools) {
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="模版下载" href="' . url('/admin/SuperSubsidy/brand/itemList/getGoodsTemplate') . '" target="_blank">
<i class="fa fa-download"></i><span class="hidden-xs">模版下载</span></a></div>');
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="上传商品" href="' . url('/admin/SuperSubsidy/brand/itemList/upload') . '">
<i class="fa fa-upload"></i><span class="hidden-xs">上传商品</span></a></div>');
            });
            $grid->paginate($gridModel->getPerPage());
            $grid->filter(function (Grid\Filter $filter) use ($brandOption) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($brandOption) {
                    $filter->equal('brand_user_id', '品牌账户')->select($brandOption);
                });
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('item_id', '有赞商品id');
                    $filter->equal('item_name', '商品名称');
                });
            });
            $grid->disableExport();
            $grid->disableBatchActions();
            $grid->column('id', 'id');
            $grid->column('brand_name', '品牌名称');
            $grid->column('item_id', '有赞商品id')->copyable();
            $grid->column('item_name', '商品名称');
            $grid->column('sku_id', '规格id')->display(function () {
                return $this->sku_id ?: '';
            });
            $grid->column('sku_name', '规格名称');
            $grid->column('supply_price', '供货价');
            $grid->column('market_price', '市场价');
            $grid->column('hhz_price', '好好住价格');
            $grid->column('commission', '结算价');
            $grid->column('update_at', '更新时间')->display(function () {
                return strtotime($this->update_at) > 0 ? date('Y-m-d H:i:s', strtotime($this->update_at)) : '-';
            });
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
            });
        });
        $tab = new Tab();
        $tab->add('品牌商品列表', $grid->render(), true);
        $tab->addLink('品牌提交到商品库', url('/admin/SuperSubsidy/brand/goodsList'));
        $content->row($tab);
        return $content
            ->header("超级补贴 | 品牌商品列表")
            ->description(' ')
            ->breadcrumb(['text' => '超级补贴 | 品牌商品列表', 'url' => url('/admin/SuperSubsidy/brand/itemList')], ['text' => '商品列表']);
    }

    public function itemEdit(Request $request, Content $content, $id = 0)
    {
        $info = [];
        if ($id) {
            $info = YouZanBrandItemModel::getByWhere(['id' => $id]);
        }
        $userList = YouZanBrandUserModel::selectByWhere([], ['id', 'brand_name']);
        $userListOption = array_column($userList, 'brand_name', 'id');
        $form = new Form($info);
        $form->hidden('id', 'id');
        $form->select('brand_user_id', '品牌')->options($userListOption)->setWidth(4, 2);
        if ($info) {
            $form->text('item_id', '有赞商品ID')->required()->setWidth(4, 2)->readonly();
        } else {
            $form->text('item_id', '有赞商品ID')->required()->setWidth(4, 2);
        }
        $form->text('item_name', '商品名称')->required()->setWidth(4, 2);
        $form->text('sku_id', '规格ID')->setWidth(4, 2);
        $form->text('sku_name', '规格名称')->setWidth(4, 2);
        $form->decimal('supply_price', '供货价')->required()->setWidth(4, 2);
        $form->decimal('market_price', '市场价')->required()->setWidth(4, 2);
        $form->decimal('hhz_price', '好好住价格')->required()->setWidth(4, 2);
        $form->decimal('commission', '结算价')->required()->setWidth(4, 2);
        $form->action('/admin/SuperSubsidy/brand/itemList/itemSave');
        return $content
            ->header('超级补贴 | 编辑商品')
            ->description(' ')
            ->breadcrumb(
                ['text' => '超级补贴 | 品牌商品列表', 'url' => url('/admin/SuperSubsidy/brand/itemList')],
                ['text' => '编辑商品']
            )
            ->row($form->render());
    }

    public function itemSave(Request $request, Content $content)
    {
        try {
            $id = $request->input('id', 0);
            $brandUserId = $request->input('brand_user_id', 0);
            if (empty($brandUserId)) {
                throw new \Exception('请选择一个品牌');
            }
            $itemId = $request->input('item_id', 0);
            $itemName = $request->input('item_name', '');
            $skuId = $request->input('sku_id', 0);
            $skuName = $request->input('sku_name', '');
            $supplyPrice = $request->input('supply_price', 0);
            $marketPrice = $request->input('market_price', 0);
            $hhzPrice = $request->input('hhz_price', 0);
            $commission = $request->input('commission', 0);
            if (!$itemId || !$itemName || $supplyPrice < 0.01 || $marketPrice < 0.01 || $hhzPrice < 0.01) {
                throw new \Exception('必填信息不完整');
            }
            $data = [
                'brand_user_id' => $brandUserId,
                'item_id' => $itemId,
                'item_name' => $itemName,
                'sku_id' => $skuId,
                'sku_name' => $skuName,
                'supply_price' => $supplyPrice,
                'market_price' => $marketPrice,
                'commission' => $commission,
                'hhz_price' => $hhzPrice,
                'admin_id' => Admin::user()->id,
            ];
            $info = $id ? YouZanBrandItemModel::getByWhere(['id' => $id]) : [];
            $res = false;
            if ($info) {
                $res = YouZanBrandItemModel::updateData($data, ['id' => $id]);
            } else {
                $info = YouZanBrandItemModel::getByWhere(['item_id' => $itemId, 'sku_id' => $skuId]);
                if ($info) {
                    $res = YouZanBrandItemModel::updateData($data, ['id' => $info['id']]);
                } else {
                    $res = YouZanBrandItemModel::insertData($data);
                }
            }
            if ($res) {
                YouZanBrandItemModel::updateData(['brand_user_id' => $brandUserId], ['item_id' => $itemId]);
                YouZanOrders::updateData(['brand_user_id' => $brandUserId], ['item_id' => $itemId]);
                $success = new MessageBag([
                    'title' => '创建成功'
                ]);
                return redirect('/admin/SuperSubsidy/brand/itemList')->with(compact('success'));
            } else {
                throw new \Exception('创建失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '创建失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function getGoodsTemplate(Request $request)
    {
        try {
            $userList = YouZanBrandUserModel::selectByWhere([], 'brand_name');
            $select_str = implode(',', $userList);
            $sheetData = $this->getSheetData();
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            foreach ($sheetData as $row) {
                $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
                $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
            }
            $objValidation = $sheet->getDataValidation("A2");
            $objValidation->setType(PHPExcel_Cell_DataValidation::TYPE_LIST);
            $objValidation->setErrorStyle(PHPExcel_Cell_DataValidation::STYLE_INFORMATION);
            $objValidation->setAllowBlank(false);
            $objValidation->setShowDropDown(true);
            $objValidation->setShowInputMessage(true);
            $objValidation->setShowErrorMessage(true);
            $objValidation->setErrorTitle("输入的值有误");
            $objValidation->setError("请输入下拉框列表内的值:" . $select_str);
            $objValidation->setPromptTitle('选择下拉框的值');
            $objValidation->setFormula1('"' . $select_str . '"');
            for ($i = 2; $i <= 200; $i++) {
                $sheet->setDataValidation("A{$i}", $objValidation);
            }
            $exportName = str_replace("+", "%20", urlencode("上传商品模版"));
            $fileName = $exportName . date('YmdHis') . '.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
        } catch (\Exception $exception) {
            Log::error('导出异常', $exception);
        }
    }

    private function getSheetData()
    {
        $sheetData = [
            ['cell_title' => '品牌', 'cell_key' => 'A', 'cell_width' => 20, 'value_key' => 'brand_name'],
            ['cell_title' => '有赞商品ID', 'cell_key' => 'B', 'cell_width' => 20, 'value_key' => 'item_id'],
            ['cell_title' => '商品名称', 'cell_key' => 'C', 'cell_width' => 30, 'value_key' => 'item_mame'],
            ['cell_title' => '规格ID(非必填)', 'cell_key' => 'D', 'cell_width' => 20, 'value_key' => 'sku_id'],
            ['cell_title' => '规格名称(非必填)', 'cell_key' => 'E', 'cell_width' => 20, 'value_key' => 'sku_name'],
            ['cell_title' => '供货价', 'cell_key' => 'F', 'cell_width' => 15, 'value_key' => 'supply_price'],
            ['cell_title' => '市场价', 'cell_key' => 'G', 'cell_width' => 15, 'value_key' => 'market_price'],
            ['cell_title' => '好好住价格', 'cell_key' => 'H', 'cell_width' => 18, 'value_key' => 'hhz_price'],
            ['cell_title' => '结算价', 'cell_key' => 'I', 'cell_width' => 18, 'value_key' => 'commission'],
        ];
        return $sheetData;
    }


    public function upload(Request $request, Content $content)
    {
        $info = ['file' => ''];
        $form = new Form($info);
        $form->file('file', '上传商品文件')->help('文件格式为：excel文件');
        $form->action('/admin/SuperSubsidy/brand/itemList/batchAdd');
        return $content
            ->header('上传品牌商品文件')
            ->description(' ')
            ->breadcrumb(
                ['text' => '超级补贴 | 品牌商品列表', 'url' => url('/admin/SuperSubsidy/brand/itemList')],
                ['text' => '上传品牌商品文件']
            )
            ->row($form->render());
    }

    public function batchAdd(Request $request)
    {
        try {
            $file = $request->file('file');
            $fileName = '/tmp/brandGoods-' . date('YmdHis') . '.xls';
            $res = move_uploaded_file($file, $fileName);
            $spreadsheet = IOFactory::load($fileName);
            $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
            $data = [];
            $tempSheetTitle = $this->getSheetData();
            $tempSheetTitle = array_column($tempSheetTitle, 'cell_title');
            if ($sheetData && is_array($sheetData)) {
                foreach ($sheetData as $i => $item) {
                    if ($i <= 1) {
                        $sheetTitles = array_values($item);
                        $sheetTitles = array_filter($sheetTitles);
                        $diff1 = array_diff($sheetTitles, $tempSheetTitle);
                        $diff2 = array_diff($tempSheetTitle, $sheetTitles);
                        if (count($sheetTitles) != count($tempSheetTitle) || $diff1 || $diff2) {
                            throw new \Exception('请按照模版文件格式上传商品');
                        }
                        continue;
                    }
                    $info = [
                        'brand_name' => trim($item['A']),
                        'item_id' => trim($item['B']),
                        'item_name' => trim($item['C']),
                        'sku_id' => trim($item['D']),
                        'sku_name' => trim($item['E']),
                        'supply_price' => trim($item['F']),
                        'market_price' => trim($item['G']),
                        'hhz_price' => trim($item['H']),
                        'commission' => trim($item['I']),
                    ];
                    if ($info['brand_name'] && $info['item_id']) {
                        $data[] = $info;
                    }
                }
            }
            $adminId = Admin::user()->id;
            $res = false;
            if ($data) {
                $brandNames = array_column($data, 'brand_name');
                $brandNames = array_unique(array_filter($brandNames));
                $brandUserList = YouZanBrandUserModel::selectByWhere(['brand_name' => $brandNames], ['brand_name', 'id']);
                $brandUserList = $brandUserList ? array_column($brandUserList, 'id', 'brand_name') : [];
                $itemBrandUserIds = [];
                foreach ($data as $row) {
                    $itemId = $row['item_id'];
                    if (!isset($itemBrandUserIds[$itemId])) {
                        $brandUserId = $brandUserList[$row['brand_name']] ?? 0;
                        $itemBrandUserIds[$itemId] = $brandUserId;
                    }
                    $brandUserId = $itemBrandUserIds[$itemId];
                    if ($brandUserId) {
                        $skuId = $row['sku_id'];
                        $addData = [
                            'brand_user_id' => $brandUserId,
                            'item_id' => $row['item_id'],
                            'item_name' => $row['item_name'],
                            'sku_id' => $skuId,
                            'sku_name' => $row['sku_name'],
                            'supply_price' => $row['supply_price'],
                            'market_price' => $row['market_price'],
                            'hhz_price' => $row['hhz_price'],
                            'commission' => $row['commission'],
                            'admin_id' => $adminId
                        ];
                        $info = YouZanBrandItemModel::getByWhere(['item_id' => $itemId, 'sku_id' => $skuId]);
                        if ($info) {
                            $res = YouZanBrandItemModel::updateData($addData, ['id' => $info['id']]);
                        } else {
                            $res = YouZanBrandItemModel::insertData($addData);
                        }
                        if ($res) {
                            YouZanBrandItemModel::updateData(['brand_user_id' => $brandUserId], ['item_id' => $itemId]);
                            $res = YouZanOrders::updateData(['brand_user_id' => $brandUserId], ['item_id' => $itemId]);
                        }
                    }
                }
            }
            if ($res) {
                $success = new MessageBag([
                    'title' => '上传成功'
                ]);
                return redirect('/admin/SuperSubsidy/brand/itemList')->with(compact('success'));
            } else {
                throw new \Exception('上传失败');
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '上传失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

}